//
//  FormalTestController.m
//  Drivinglicense
//
//  Created by HappyMilk 02 on 2017/6/29.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "FormalTestController.h"
#import "LoginHeader.h"
#import "FormalViewCell.h"
#import "QuestionModel.h"
#import <UIImageView+WebCache.h>
#import <SVProgressHUD.h>
#import "PassViewController.h"

@interface FormalTestController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *view_nav;
@property (weak, nonatomic) IBOutlet UILabel *lab_time;
@property (weak, nonatomic) IBOutlet UILabel *lab_question;
@property (weak, nonatomic) IBOutlet UIImageView *imgv_ques;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgv_height;

@property (weak, nonatomic) IBOutlet UILabel *lab_ans1;
@property (weak, nonatomic) IBOutlet UILabel *lab_ans2;
@property (weak, nonatomic) IBOutlet UILabel *lab_ans3;
@property (weak, nonatomic) IBOutlet UILabel *lab_ans4;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *lab_ans_arr;

@property (weak, nonatomic) IBOutlet UIButton *btn_ans1;
@property (weak, nonatomic) IBOutlet UIButton *btn_ans2;
@property (weak, nonatomic) IBOutlet UIButton *btn_ans3;
@property (weak, nonatomic) IBOutlet UIButton *btn_ans4;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btn_ans_arr;

@property (weak, nonatomic) IBOutlet UILabel *lab_test_num;
@property (weak, nonatomic) IBOutlet UIButton *btn_true_num;
@property (weak, nonatomic) IBOutlet UIButton *btn_false_num;
@property (weak, nonatomic) IBOutlet UIButton *btn_down_up;

//
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIView *view_collect;

//当前题目
@property (nonatomic ,strong) QuestionModel *currentModel;
//考题序号
@property (nonatomic) NSInteger num_question;


@property (nonatomic ,strong) UIView *view_alert;

@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic ,strong) GADBannerView *bannerView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height_lab_const;

@end

static NSString *const reuseIdentifier = @"FormalViewCell";
@implementation FormalTestController

- (IBAction)popvc:(id)sender {
    [self createHintView:1];
}
//倒计时
static int allTime = 2700;
- (void)computingTime:(NSTimer *)timer{
    
    int mm = allTime/60;
    int ss = allTime%60;
    if (ss>9) {
        self.lab_time.text = [NSString stringWithFormat:@"倒计时 %d:%d",mm,ss];
    }else{
        self.lab_time.text = [NSString stringWithFormat:@"倒计时 %d:0%d",mm,ss];
    }
    if (allTime == 0) {
        [timer invalidate];
        [self createHintView:3];
    }
    allTime--;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    allTime = 2700;
    // Do any additional setup after loading the view.
    self.view_nav.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    self.view_nav.layer.shadowOffset = CGSizeMake(0,2);
    self.view_nav.layer.shadowRadius = 2;
    self.view_nav.layer.shadowOpacity = 0.4;
    
    self.height_lab_const.constant = IS_IPAD?100:60;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(computingTime:) userInfo:nil repeats:YES];
    
    [self loadQuestion:0];
    
    [self createCollectionView];
    
    if (IS_PASS && IS_CHINESE) {
        
        self.bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait origin:(CGPoint){0,70}];
        [self.view addSubview:_bannerView];
        _bannerView.adUnitID = AD_TEST_HF;//@"ca-app-pub-4634576436183649/5385133417"@"ca-app-pub-3940256099942544/2934735716"
        _bannerView.rootViewController = self;
        [_bannerView loadRequest:[GADRequest request]];
    }
    [self.view bringSubviewToFront:self.view_collect];
}

- (void)createHintView:(NSInteger)type{
    
    self.view_alert = [[UIView alloc] initWithFrame:(CGRect){__kwidth/2-150,__kheight/2-70,300,140}];
    self.view_alert.backgroundColor = [UIColor whiteColor];
    self.view_alert.layer.cornerRadius = 8;
    self.view_alert.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    self.view_alert.layer.shadowOffset = CGSizeMake(0,2);
    self.view_alert.layer.shadowRadius = 2;
    self.view_alert.layer.shadowOpacity = 0.4;
    [self.view addSubview:self.view_alert];
    [self.view bringSubviewToFront:self.view_alert];
    //self.view_alert.hidden = YES;
    
    UILabel *lab = [[UILabel alloc] initWithFrame:(CGRect){0,30,300,40}];
    if (type == 0) {
        lab.text = @"你已答错11题，成绩不合格!";
    }else if (type == 3){
        lab.text = @"考试时间结束！";
    }else{
        lab.text = [NSString stringWithFormat:@"你已回答了%ld题，确定要结束考试吗?",self.num_question];
    }
    lab.textAlignment = NSTextAlignmentCenter;
    lab.textColor = RGB(64, 63, 63);
    lab.font = [UIFont systemFontOfSize:14];
    [self.view_alert addSubview:lab];
    
    UIButton *btn1 = [[UIButton alloc] initWithFrame:(CGRect){300/2-110,90,80,30}];
    btn1.layer.cornerRadius = 8;
    btn1.layer.masksToBounds = YES;
    btn1.layer.borderWidth = 1;
    btn1.layer.borderColor = RGB(145, 141, 141).CGColor;
    [btn1.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btn1 setTitle:@"继续答题" forState:UIControlStateNormal];
    [btn1 setTitleColor:RGB(64, 63, 63) forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(continueAction) forControlEvents:UIControlEventTouchUpInside];
    if (type == 1 | type == 2) {
        [self.view_alert addSubview:btn1];
    }
    
    UIButton *btn2 = [[UIButton alloc] initWithFrame:(CGRect){300/2+30,90,80,30}];
    if (type == 0 || type == 3) {
        btn2.frame = (CGRect){300/2-40,90,80,30};
    }
    [btn2.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btn2 setBackgroundImage:[UIImage imageNamed:@"t_btn_bg"] forState:UIControlStateNormal];
    if (type == 0 || type == 3) {
        btn2.tag = 0;
        [btn2 setTitle:@"交卷" forState:UIControlStateNormal];
    }else{
        btn2.tag = type;
        [btn2 setTitle:@"结束" forState:UIControlStateNormal];
    }
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(handInAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view_alert addSubview:btn2];
}
- (void)continueAction{
    [self.view_alert removeFromSuperview];
}
- (void)handInAction:(UIButton *)btn{
    if (btn.tag == 0 || btn.tag == 2) {//交卷
        [self.timer invalidate];
        NSDictionary *dic = @{@"right":self.btn_true_num.titleLabel.text,
                              @"false":self.btn_false_num.titleLabel.text,
                              @"time":[NSString stringWithFormat:@"%d",allTime]};
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        PassViewController *vc = [sb instantiateViewControllerWithIdentifier:@"PassViewController"];
        vc.dataDic = dic;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{//放弃
        [self.timer invalidate];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}




- (void)loadQuestion:(NSInteger)num{
    
    if ([self.btn_false_num.titleLabel.text integerValue]>10) {
        [self createHintView:0];
        return;
    }
    self.num_question = num;
    self.lab_test_num.text = [NSString stringWithFormat:@"%ld/100",num+1];
    
    QuestionModel *model = self.testArray[num];
    self.currentModel = model;
    //题目
    self.lab_question.text = [NSString stringWithFormat:@"%ld、%@",num+1,model.question];
    //图片
    if (IsNilString(model.pic)) {
        self.imgv_height.constant = 0;
    }else{
        self.imgv_height.constant = 190;
        [self.imgv_ques sd_setImageWithURL:[NSURL URLWithString:model.pic]];
    }
    //答案选项
    if ([model.answer isEqualToString:@"对"] | [model.answer isEqualToString:@"错"]) {
        self.lab_ans1.text = @"对";
        self.lab_ans2.text = @"错";
        self.lab_ans3.hidden = YES;
        self.lab_ans4.hidden = YES;
        self.btn_ans3.hidden = YES;
        self.btn_ans4.hidden = YES;
    }else{
        self.lab_ans3.hidden = NO;
        self.lab_ans4.hidden = NO;
        self.btn_ans3.hidden = NO;
        self.btn_ans4.hidden = NO;
        self.lab_ans1.text = model.option1;
        self.lab_ans2.text = model.option2;
        self.lab_ans3.text = model.option3;
        self.lab_ans4.text = model.option4;
    }
    
    //刷新试卷界面
    [self.collectionView reloadData];
}

//交卷
- (IBAction)handInTest:(UIButton *)sender {
    
    [self createHintView:2];
}
//提交答案
- (IBAction)handInAnswer:(UIButton *)sender {
    UIButton *selBtn;
    BOOL is_sel = NO;
    for (UIButton *btn in self.btn_ans_arr) {
        if (btn.selected == YES) {
            selBtn = btn;
            is_sel = YES;
        }
        btn.selected = NO;
    }
    if (selBtn == nil) {
        [SVProgressHUD showInfoWithStatus:@"请选者答案"];
        return;
    }
    UILabel *lab = self.lab_ans_arr[selBtn.tag];
    
    
    //判断题
    if ([self.currentModel.answer isEqualToString:@"对"] | [self.currentModel.answer isEqualToString:@"错"]){
        
        if ([lab.text isEqualToString:self.currentModel.answer]) {//正确
            QuestionModel *model = self.testArray[self.num_question];
            model.is_right = 1;
            [self.btn_true_num setTitle:[NSString stringWithFormat:@"%ld",[self.btn_true_num.titleLabel.text integerValue]+1] forState:UIControlStateNormal];
        }else{//错误
            QuestionModel *model = self.testArray[self.num_question];
            model.is_right = 2;
            [self.btn_false_num setTitle:[NSString stringWithFormat:@"%ld",[self.btn_false_num.titleLabel.text integerValue]+1] forState:UIControlStateNormal];
        }
        
        //下一题
        [self loadQuestion:self.num_question+1];
        
        return;
    }
    //选择题
    NSString *anstr = [lab.text substringToIndex:1];
    if ([anstr isEqualToString:self.currentModel.answer]) {//正确
        QuestionModel *model = self.testArray[self.num_question];
        model.is_right = 1;
        [self.btn_true_num setTitle:[NSString stringWithFormat:@"%ld",[self.btn_true_num.titleLabel.text integerValue]+1] forState:UIControlStateNormal];
    }else{//错误
        QuestionModel *model = self.testArray[self.num_question];
        model.is_right = 2;
        [self.btn_false_num setTitle:[NSString stringWithFormat:@"%ld",[self.btn_false_num.titleLabel.text integerValue]+1] forState:UIControlStateNormal];
    }
    //下一题
    [self loadQuestion:self.num_question+1];
}
//选择答案
- (IBAction)selectedAnswer:(UIButton *)sender {
    for (UIButton *btn in self.btn_ans_arr) {
        if ([btn isEqual:sender]) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    
}

//弹出收回试卷界面
- (IBAction)downUpAction:(UIButton *)sender {
    if (sender.selected) {//收回
        sender.selected = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.view_collect.frame = (CGRect){0,__kheight-45,__kwidth,260};
        } completion:^(BOOL finished) {
            
        }];
    }else{//弹出
        sender.selected = YES;
        [UIView animateWithDuration:0.3 animations:^{
            self.view_collect.frame = (CGRect){0,__kheight-260,__kwidth,260};
        } completion:^(BOOL finished) {
            
        }];
    }
}



#pragma mark --- 试卷collection
- (void)createCollectionView{
    //self.view_collect.frame = (CGRect){0,__kheight-45,__kwidth,260};
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"FormalViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = __kwidth/10;
    flowLayout.itemSize = CGSizeMake(width, width);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.collectionViewLayout = flowLayout;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.testArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    QuestionModel *model = self.testArray[indexPath.row];
    FormalViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.view_bg.backgroundColor = [UIColor whiteColor];
    if (model.is_right == 1) {
        cell.view_bg.backgroundColor = RGBA(31, 146, 255, 0.46);
    }else if(model.is_right == 2){
        cell.view_bg.backgroundColor = RGBA(244, 42, 42, 0.46);
    }
    cell.lab_num.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
